package com.system.service.impl;

import com.system.mapper.AddressMapper;
import com.system.mapper.ClientMapper;
import com.system.pojo.Address;
import com.system.pojo.Client;
import com.system.service.AddressService;
import com.system.vo.ResultVo;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yjymm
 * @date 2019-12-13 21:46
 */
@Service
public class AddressServiceImpl implements AddressService {

	@Autowired
	private AddressMapper addressMapper;

	@Autowired
	private ClientMapper clientMapper;

	@Override
	public ResultVo<Address> insert(Address address) {
		ResultVo<Address> resultVo = new ResultVo<Address>();
		boolean defaultAddress = address.isDefaultAddress();
		int i = addressMapper.insertSelective(address);
		if (i == 1) {
			if (defaultAddress) {
				Integer addressId = address.getId();
				Integer clientId = address.getClientId();
				Client client = new Client();
				client.setId(clientId);
				client.setAddressId(addressId);
				clientMapper.updateByPrimaryKeySelective(client);
			}
			resultVo.setInsert(true);
			resultVo.setMessage("收获地址添加成功");
		} else {
			resultVo.setMessage("收获地址添加成功失败");
		}
		return resultVo;
	}

	@Override
	public ResultVo<Address> detail(Integer addressId) {
		ResultVo<Address> resultVo = new ResultVo<Address>();
		Address address = addressMapper.selectByPrimaryKey(addressId);
		resultVo.setT(address);
		resultVo.setMessage("查询成功");
		return resultVo;
	}

	@Override
	public ResultVo<Address> update(Address address) {
		ResultVo<Address> resultVo = new ResultVo<Address>();
//        Address address = addressMapper.selectByPrimaryKey(addressId);
//        resultVo.setT(address);
		int i = addressMapper.updateByPrimaryKeySelective(address);
		if (i != 1) {
			throw new RuntimeException();
		}
		resultVo.setMessage("更新成功");
		return resultVo;
	}

	
	@Override
	public ResultVo<Address> delete(Integer addressId, Integer clientId) {
		ResultVo<Address> resultVo = new ResultVo<Address>();
		Client client = clientMapper.selectByPrimaryKey(clientId);
		List<Address> addresses = client.getAddresses();
		if (addresses.size() == 1) {
			//只有一个收获地址
			client.setAddressId(null);
			
		}else {
			for (Address address : addresses) {
				if (address.getId() != addressId) {
					client.setAddressId(address.getId());
					break;
				}
			}
		}
		
		clientMapper.updateByPrimaryKeySelective(client);
		addressMapper.deleteByPrimaryKey(addressId);
		resultVo.setDelete(true);
		resultVo.setMessage("删除成功");
		return resultVo;
	}
}
